<template>
    <n-scrollbar class="px-4" ref="scrollbarRef">
        <template v-for="message in messages">
            <chat-message-self v-if="message.type === ChatMessageType.SELF" :message="message" class="mt-3"/>
            <chat-message-other v-if="message.type === ChatMessageType.OTHER" :message="message" class="mt-3"/>
            <chat-message-system v-if="message.type === ChatMessageType.SYSTEM" :message="message" class="mt-3"/>
        </template>
    </n-scrollbar>
</template>

<script setup lang="ts">
import ChatMessageSelf from "./chat-message-self.vue";
import ChatMessageOther from "./chat-message-other.vue";
import ChatMessageSystem from "./chat-message-system.vue";

import { nextTick, ref, watch } from "vue";
import { ScrollbarInst } from "naive-ui";

import { ChatMessageType, IChatMessage } from "./chat-message.ts";

const props = defineProps<{
    messages: IChatMessage[]
}>();

const scrollbarRef = ref<ScrollbarInst & { scrollbarInstRef: { containerRef: HTMLElement, contentRef: HTMLElement } }>();

// 当修改消息列表时, 如果消息框的滚动条在最底端, 那么进行自动滚动
watch(() => props.messages.length, (value, oldValue) => {
    if (value > oldValue) {
        const containerRef = scrollbarRef.value?.scrollbarInstRef?.containerRef;
        if (containerRef) {
            // 计算滚动条是否大约在最底部
            if (Math.abs(containerRef.scrollHeight - containerRef.clientHeight - containerRef.scrollTop) < 10) {
                // 必须使用nextTick, 等待array真实被修改后且DOM元素变更 执行滚动
                nextTick(() => {
                    scrollbarRef.value!.scrollTo({
                        top: containerRef.scrollHeight - containerRef.clientHeight
                    });
                });
            }
        }
    }
});


</script>


<style scoped>

</style>